export default function applyMiddleware(...middlewares) {
  return createStore => (reducer, preloadedState, enhancer) => {
    var store = createStore(reducer, preloadedState, enhancer);
    var dispatch = store.dispatch;
    var chains = [];

    var middlewareAPI = {
      getState: store.getState,
      dispatch: action => dispatch(action),
    };

    chains = middlewares.map(middleware => middleware(middlewareAPI));
    dispatch = compose(...chains)(store.dispatch);

    return { ...store, dispatch };
  };
}
